#!/usr/bin/python
# -*- coding: utf-8 -*-

import os
import re
import urllib
import sys

def removeTags(text,tag='.*'):
    tagsInText = re.findall('[<]%s[>]' % tag,text)
    for tag in tagsInText:
        text = text.replace(tag,'')
    return text

class kontextParser:

    def __init__(self,content):
        self.content = content.lower()
        self.contentOrg = content
        self.specialTags = {'a':'a '}
        self.splitTags = ['br']
        self.unclosedTags = {'dt':['dt','/dl'],
                             'li':['li','/ul'],
                             'link':['link','/head']}

    def getPositionsOfTag(self,_tag):
        _start = 0
        ret = []
        if _tag in self.specialTags:
            _tag = self.specialTags[_tag]
        if not _tag in self.unclosedTags:
            __tag = '%s.*?' % _tag
        else:
            __tag = _tag
        if _tag in self.splitTags:
            return self.content.split('<%s>'%_tag)
        sTags = self.getTags(__tag,self.content)
        eTag  = '</%s>' % _tag.split()[0]
        pTag  = '<%s' % _tag
        for tag in sTags:
            startPos = self.content.find(tag,_start)
            if _tag in self.unclosedTags:
                tempPos = []
                for ends in self.unclosedTags[_tag]:
                    _firstPossible = self.content.find('<%s>'%ends,startPos+len(tag))
                    if not _firstPossible==-1:
                        tempPos.append(self.content.find('<%s>'%ends,startPos+len(tag)))
                possibleEndPos = min(tempPos)
            else:
                possibleEndPos = self.content.find(eTag,startPos)
                eCount = self.content[startPos+len(tag):possibleEndPos].count(eTag)
                sCount = self.content[startPos+len(tag):possibleEndPos].count(pTag)
                while not eCount==sCount:
                    _startPos = possibleEndPos + len(eTag)
                    possibleEndPos = self.content.find(eTag,_startPos)
                    eCount = self.content[_startPos+len(tag):possibleEndPos].count(eTag)
                    sCount = self.content[_startPos+len(tag):possibleEndPos].count(pTag)

            ret.append({'tagContent':tag,'startPos':startPos+len(tag),'endPos':possibleEndPos})
            _start = startPos + len(tag)
        return ret

    def getElementByTag(self,_tag):
        res = self.getPositionsOfTag(_tag)
        ret = []
        for i in res:
            ret.append(self.contentOrg[i['startPos']:i['endPos']])
            #ret.append(self.getAttr(i['tagContent'],'href'))
        return ret

    def getTags(self,tag,text):
        return re.findall('[<]%s[>]' % tag,text)

    def getAttr(self,text,attr):
        pi = re.findall('%s=[\'|\"].*?[\'|\"]' % attr,text)
        return pi[0][len(attr)+2:-1]

if __name__=="__main__":
    content = file(sys.argv[2],'r').read()
    kontext = kontextParser(content)
    res = kontext.getElementByTag(sys.argv[1])
    for i in res:
        if '--notags' in sys.argv:
            print removeTags(i),'\n'
        else:
            print i,'\n'
        print '-'*20,'\n'
